// 引入API和DataTable
// 确保已加载 api.js 和 data-table.js

// 订单管理脚本
document.addEventListener('DOMContentLoaded', function() {
    // 初始化订单表格
    initOrderTable();
});

// 初始化订单表格
function initOrderTable() {
    // 订单表格列定义，根据OrderDTO的字段定义
    const orderColumns = [
        { field: 'id', title: '订单ID', readonly: true },
        { field: 'orderNumber', title: '订单编号', readonly: true },
        { field: 'userId', title: '用户ID', readonly: true },
        { field: 'totalAmount', title: '订单金额', type: 'number', readonly: true },
        { field: 'totalQuantity', title: '商品总数', type: 'number', readonly: true },
        { field: 'status', title: '订单状态', type: 'select', options: [
            { value: '待付款', label: '待付款' },
            { value: '已付款', label: '已付款' },
            { value: '已发货', label: '已发货' },
            { value: '已完成', label: '已完成' },
            { value: '已取消', label: '已取消' }
        ]},
        { field: 'address', title: '收货地址', type: 'textarea' },
        { field: 'phone', title: '联系电话' },
        { field: 'createdAt', title: '创建时间', readonly: true, formatter: formatDateTime }
    ];
    
    // 初始化订单表格
    const orderTable = new DataTable('order-content', orderColumns, OrderAPI);

    // 添加发货操作按钮
    orderTable.addCustomAction({
        name: '发货',
        icon: 'fas fa-shipping-fast',
        visible: (order) => order.status === '已付款', // 只有已付款的订单显示发货按钮
        handler: shipOrder
    });
    
    // 添加订单详情查看功能
    orderTable.addCustomAction({
        name: '查看详情',
        icon: 'fas fa-eye',
        handler: viewOrderDetail
    });
}

// 发货处理函数
function shipOrder(order) {
    if (confirm(`确定要为订单 #${order.orderNumber || order.id} 发货吗？`)) {
        // 显示加载中
        const loadingMsg = layer.msg('正在处理...', {
            icon: 16,
            shade: 0.3,
            time: 0
        });
        
        // 调用更新状态API
        OrderAPI.updateStatus(order.id,'已发货')
            .then(response => {
                layer.close(loadingMsg);
                
                if (response) {
                    layer.msg('发货成功！', {icon: 1});
                    // 刷新表格数据
                    document.querySelector('#order-content .refresh-btn').click();
                } else {
                    layer.msg(response.message || '发货失败', {icon: 2});
                }
            })
            .catch(error => {
                layer.close(loadingMsg);
                console.error('发货出错:', error);
                layer.msg('发货失败，请稍后再试', {icon: 2});
            });
    }
}

// 格式化日期时间
function formatDateTime(value) {
    if (!value) return '';
    
    // 如果是字符串，尝试转换为日期对象
    let date = typeof value === 'string' ? new Date(value) : value;
    
    // 检查是否是有效日期
    if (isNaN(date.getTime())) return value;
    
    // 格式化为 YYYY-MM-DD HH:MM:SS
    return date.getFullYear() + '-' + 
           padZero(date.getMonth() + 1) + '-' + 
           padZero(date.getDate()) + ' ' + 
           padZero(date.getHours()) + ':' + 
           padZero(date.getMinutes()) + ':' + 
           padZero(date.getSeconds());
}

// 数字补零
function padZero(num) {
    return num < 10 ? '0' + num : num;
}

// 查看订单详情
function viewOrderDetail(order) {
    // 获取订单详情
    axios.get(`/orders/${order.id}`)
        .then(response => {
            if (response.data.success) {
                const orderDetail = response.data.data;
                showOrderDetailModal(orderDetail);
            } else {
                console.error('获取订单详情失败:', response.data.message);
                alert('获取订单详情失败: ' + response.data.message);
            }
        })
        .catch(error => {
            console.error('获取订单详情出错:', error);
            alert('获取订单详情出错，请稍后再试');
        });
}

// 显示订单详情模态框
function showOrderDetailModal(order) {
    // 创建模态框HTML
    let modalHtml = `
        <div class="modal-header">
            <h3>订单详情 - ${order.orderNumber}</h3>
            <button class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
            <div class="order-info">
                <div class="info-group">
                    <label>订单编号:</label>
                    <span>${order.orderNumber}</span>
                </div>
                <div class="info-group">
                    <label>创建时间:</label>
                    <span>${formatDateTime(order.createdAt)}</span>
                </div>
                <div class="info-group">
                    <label>订单状态:</label>
                    <span>${getOrderStatusText(order.status)}</span>
                </div>
                <div class="info-group">
                    <label>订单金额:</label>
                    <span>￥${order.totalAmount.toFixed(2)}</span>
                </div>
                <div class="info-group">
                    <label>收货地址:</label>
                    <span>${order.address || '无'}</span>
                </div>
                <div class="info-group">
                    <label>联系电话:</label>
                    <span>${order.phone || '无'}</span>
                </div>
            </div>
            
            <h4>订单商品</h4>
            <table class="detail-table">
                <thead>
                    <tr>
                        <th>商品名称</th>
                        <th>单价</th>
                        <th>数量</th>
                        <th>小计</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    // 添加订单项
    if (order.items && order.items.length > 0) {
        order.items.forEach(item => {
            modalHtml += `
                <tr>
                    <td>${item.bookName || '未知商品'}</td>
                    <td>￥${item.price ? item.price.toFixed(2) : '0.00'}</td>
                    <td>${item.quantity}</td>
                    <td>￥${(item.price * item.quantity).toFixed(2)}</td>
                </tr>
            `;
        });
    } else {
        modalHtml += `
            <tr>
                <td colspan="4" class="text-center">无商品信息</td>
            </tr>
        `;
    }
    
    modalHtml += `
                </tbody>
            </table>
        </div>
        <div class="modal-footer">
            <button class="btn-primary close-modal">关闭</button>
        </div>
    `;
    
    // 创建模态框元素
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.innerHTML = modalHtml;
    
    // 创建模态框背景
    const modalBg = document.createElement('div');
    modalBg.className = 'modal-bg';
    
    // 添加到页面
    document.body.appendChild(modalBg);
    document.body.appendChild(modal);
    
    // 绑定关闭事件
    const closeBtn = modal.querySelector('.close-btn');
    const closeModalBtn = modal.querySelector('.close-modal');
    
    closeBtn.addEventListener('click', closeModal);
    closeModalBtn.addEventListener('click', closeModal);
    modalBg.addEventListener('click', closeModal);
    
    function closeModal() {
        document.body.removeChild(modal);
        document.body.removeChild(modalBg);
    }
}

// 获取订单状态文本
function getOrderStatusText(status) {
    switch (status) {
        case 'PENDING': return '待付款';
        case 'PAID': return '已付款';
        case 'SHIPPED': return '已发货';
        case 'DELIVERED': return '已送达';
        case 'COMPLETED': return '已完成';
        case 'CANCELLED': return '已取消';
        default: return '未知状态';
    }
}